<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Imgur extends Model
{
    protected $fillable = [
        'title',
        'title_translation',
        'keyword',
        'imgur_id',
        'is_published'
    ];


    static public function insertSpiderJson($obj){

        $imgur_id = $obj->id;
        $title = $obj->title;
        //$description = $obj->description;
        $instance = Imgur::updateOrCreate(compact('imgur_id'),compact('title'));
        //已删除了
        if(!empty($instance->deleted_at)){
            return;
        }

        if($obj->is_album){
            foreach ($obj->images as $value){
                $link = $value->link;
                $key = 'imgur_'.$value->id;
                $description = $value->description ;
                if(empty($description)){
                    $description = $value->title ;
                }
                if(empty($description)){
                    $description = $title ;
                }
                $img_instance = Image::fetchUrlWithKey($link,$key,$description);
                if($img_instance->id >0){
                    $img_instance->imgur_id = $instance->id;
                    $img_instance->width = $value->width;
                    $img_instance->height =$value->height;
                    $img_instance->fsize = $value->bandwidth;
                    $img_instance->format = $value->bandwidth;
                    $img_instance->save();
                }
            }
        }else {
            $value = $obj;

            $link = $value->link;
            $key = 'imgur_'.$value->id;
            $description = $value->description ;
            if(empty($description)){
                $description = $value->title ;
            }
            if(empty($description)){
                $description = $title ;
            }
            $img_instance = Image::fetchUrlWithKey($link,$key,$description);
            if($img_instance->id >0){
                $img_instance->imgur_id = $instance->id;
                $img_instance->width = $value->width;
                $img_instance->height =$value->height;
                $img_instance->fsize = $value->bandwidth;
                $img_instance->format = $value->bandwidth;
                $img_instance->save();
            }
        }
    }
    public function images()
    {
        return $this->hasMany('App\Image')->orderBy('updated_at', 'desc');
    }

}
